<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>golang一门神奇的语言之一:反射实现函数调用，各种调 | Jin Tian</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  
  
  
  <meta name="description" content="Golang的学习礼记">
<meta property="og:type" content="article">
<meta property="og:title" content="Golang一门神奇的语言之一:反射实现函数调用，各种调">
<meta property="og:url" content="http://yoursite.com/2017/06/15/Golang一门神奇的语言之一-反射实现函数调用，各种调/index.html">
<meta property="og:site_name" content="Jin Tian">
<meta property="og:description" content="Golang的学习礼记">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2017-06-15T05:10:09.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Golang一门神奇的语言之一:反射实现函数调用，各种调">
<meta name="twitter:description" content="Golang的学习礼记">
  
    <link rel="alternate" href="/atom.xml" title="Jin Tian" type="application/atom+xml">
  

  

  <link rel="icon" href="/css/images/mylogo.jpg">
  <link rel="apple-touch-icon" href="/css/images/mylogo.jpg">
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link href="https://fonts.googleapis.com/css?family=Open+Sans|Montserrat:700" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic" rel="stylesheet" type="text/css">
  <link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
  <style type="text/css">
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/9749f0/00000000000000000001008f/27/l?subset_id=2&fvd=n5) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/90cf9f/000000000000000000010091/27/l?subset_id=2&fvd=n7) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/8a5494/000000000000000000013365/27/l?subset_id=2&fvd=n4) format("woff2");font-weight:lighter;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/d337d8/000000000000000000010095/27/l?subset_id=2&fvd=i4) format("woff2");font-weight:400;font-style:italic;}</style>
  <link rel="stylesheet" href="/css/style.css">

  <script src="/js/jquery-3.1.1.min.js"></script>
  <script src="/js/bootstrap.js"></script>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="/css/bootstrap.css" >

  
    <link rel="stylesheet" href="/css/dialog.css">
  

  

  
    <link rel="stylesheet" href="/css/header-post.css" >
  

  
  
  
    <link rel="stylesheet" href="/css/vdonate.css" >
  

</head>



  <body data-spy="scroll" data-target="#toc" data-offset="50">


  
  <div id="container">
    <div id="wrap">
      
        <header>

    <div id="allheader" class="navbar navbar-default navbar-static-top" role="navigation">
        <div class="navbar-inner">
          
          <div class="container"> 
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>

            
              <a class="brand" style="
                 border-width: 0px;  margin-top: 0px;"  
                href="#" data-toggle="modal" data-target="#myModal" >
                  <img width="124px" height="124px" alt="Hike News" src="/css/images/mylogo.jpg">
              </a>
            
            
            <div class="navbar-collapse collapse">
              <ul class="hnav navbar-nav">
                
                  <li> <a class="main-nav-link" href="/">首页</a> </li>
                
                  <li> <a class="main-nav-link" href="/archives">归档</a> </li>
                
                  <li> <a class="main-nav-link" href="/categories">分类</a> </li>
                
                  <li> <a class="main-nav-link" href="/tags">标签</a> </li>
                
                  <li> <a class="main-nav-link" href="/about">关于</a> </li>
                
                  <li> <a class="main-nav-link" href="http://luoli-luoli.com/chat">chat</a> </li>
                
                  <li><div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="" />
        <button type="submit" class="search-form-submit"></button>
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="请输入关键词..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(无标题)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div></li>
            </div>
          </div>
                
      </div>
    </div>

</header>



      
            
      <div id="content" class="outer">
        
          <section id="main" style="float:none;"><article id="post-Golang一门神奇的语言之一-反射实现函数调用，各种调" style="width: 75%; float:left;" class="article article-type-post" itemscope itemprop="blogPost" >
  <div id="articleInner" class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="thumb" class="article-title" itemprop="name">
      Golang一门神奇的语言之一:反射实现函数调用，各种调
    </h1>
  

      </header>
    
    <div class="article-meta">
      
	<a href="/2017/06/15/Golang一门神奇的语言之一-反射实现函数调用，各种调/" class="article-date">
	  <time datetime="2017-06-15T04:51:20.000Z" itemprop="datePublished">2017-06-15</time>
	</a>

      
      
	<a class="article-views">
	<span id="busuanzi_container_page_pv">
		阅读量<span id="busuanzi_value_page_pv"></span>
	</span>
	</a>

    </div>
    <div class="article-entry" itemprop="articleBody">
      
        <p>Golang的学习礼记<br><a id="more"></a></p>
<h1 id="为什么用Go"><a href="#为什么用Go" class="headerlink" title="为什么用Go"></a>为什么用Go</h1><p>这是学习Go语言一段时间以来的第一个笔记，首先说一下为什么我们要用Go语言？很多时候我们在用Python或者Java这样的解释性语言的时候，会遇到一个很蛋疼的问题。<br>对于Java，曾经被不经世事的时候被忽悠说Java是一门跨平台的语言，其实这没有错，但是说不依赖平台就有点装逼了，你用Java写一个程序可以直接分发给朋友使用？不可能，你要在朋友机器上有Java<br>运行环境才可以。我想说，WTF，这TM也敢说跨平台？？？跨平台我理解可是，我写一个病毒，在不同平台编译成二进制文件就可以直接分发到对应的所有平台上，你这不相当于是，自己说自己是老大然后立一套规矩让别人遵守吗？那万一别人不想安装这个环境呢？这时候有人就说了，Java可以把运行环境一起打包的，这个问题不大。但是又要牵扯到C++来了。你知道C++想使用一个boost这样的库，并且静态编译多蛋疼吗？有时候我们只是用其中的一个函数，却要把所有依赖或者说大部分都依赖进来，一个boost库就几百M甚至上G啊！很蛋疼。再说Python，可以说我是python的忠实粉丝。我在Python上可以找到很大的成就感，因为简单便捷。但是Python有一个致命的弱点，无法编译成二进制文件，我写一个工程，聚吧得把所有文件夹拷贝过去，还得安装对应的依赖包，可能unix系统没有痛点，但是windows就着实蛋疼了。</p>
<blockquote>
<p>为了编写一个跨平台的病毒，对用户友好的病毒，我决定放弃上述所有语言，选择Go。</p>
</blockquote>
<p>Go语言的特点是上述所有语言的痛点：</p>
<ul>
<li>Go可以编译成二进制文件，不需要太多的依赖，编写玩代码后，直接编译成二进制可执行文件；</li>
<li>Go语言速度快，这是直接面向机器码的语言，不亚于C++和C；</li>
<li>Go语言的开发效率不亚于Python，Go语言是一门静态语言，语法精简，不允许太冗余的依赖，你定义一个没有使用的变量都无法通过编译，防止了大量的无用资源浪费；</li>
<li>Go语言的logo很萌…</li>
</ul>
<p>当然还有很多优点就不一一列举了。至于为什么用Go，想必大家心里已经了然。</p>
<h1 id="Go入门第一课，反射调用函数"><a href="#Go入门第一课，反射调用函数" class="headerlink" title="Go入门第一课，反射调用函数"></a>Go入门第一课，反射调用函数</h1><p>直接进入第一课了，反射调用函数，有人会说了，execuse me？第一课就将反射？我聚吧反射都不知道啥意思好吧？？没有关系，Go语言其他的东西同志们可以去看Go Tour，基本语法很简单。我们说一下反射这个东西。大家翻一下我之前写的几篇关于Python多线程的blog就会发现反射的踪迹，反射是动态语言独有的特性，Python， Java, Swift等都有反射机制，但是Go是一门静态语言，居然也有这个特性，这不得不说这门语言是非常完美的。反射的作用是啥？很多时候我们需要调用一个函数，但是不能直接把函数名穿进去，或者说我只能把函数的字符串给你，让你来调用这个函数。这就需要用到反射。<br>闲话不多说直接上代码：<br><figure class="highlight go"><table><tr><td class="code"><pre><div class="line"><span class="keyword">package</span> main</div><div class="line"><span class="keyword">import</span> <span class="string">"fmt"</span></div><div class="line"><span class="keyword">import</span> <span class="string">"reflect"</span></div><div class="line"></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">MyMissionMethod</span><span class="params">(a <span class="keyword">string</span>)</span></span>&#123;</div><div class="line">	fmt.Println(<span class="string">"hello, world, this is my mission."</span>)</div><div class="line">	fmt.Printf(<span class="string">"and this is my params: %s \n"</span>, a)</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">CallMethod</span><span class="params">(method <span class="keyword">interface</span>&#123;&#125;)</span></span>&#123;</div><div class="line">	<span class="comment">// here method is a interface which is a type of func</span></div><div class="line">	fv := reflect.ValueOf(method)</div><div class="line">	args := []reflect.Value&#123;reflect.ValueOf(<span class="string">"金天"</span>)&#125;</div><div class="line">	fv.Call(args)</div><div class="line"></div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</div><div class="line">	mission := MyMissionMethod</div><div class="line">	CallMethod(mission)</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>这里，我callMyMissionMethod这个方法，是直接以interface这个类型去call的，明白我的意思吧？这样的话，你就有一个办法了，比如别人给我一个字符串”MyMissionMethod”，然后我要调用对应的方法，我可以做一个map，对应的value是mission,这个mission就是MyMissionMethod的interface类型，最后就可以调用之。<br>好了，就讲到这里吧，下一次blog讲解golang里面的多线程。</p>

      
    </div>
    <footer class="article-footer">
      
        <div id="donation_div"></div>

<script src="/js/vdonate.js"></script>
<script>
var a = new Donate({
  title: '骚年，加个好友打赏一下啊，现在连泡面都吃不起了啊', // 可选参数，打赏标题
  btnText: '打赏支持', // 可选参数，打赏按钮文字
  el: document.getElementById('donation_div'),
  wechatImage: 'https://i.loli.net/2017/09/27/59cb048ba6838.jpeg',
  alipayImage: 'https://i.loli.net/2017/09/27/59cb049cd0951.jpeg'
});
</script>
      
      
        
	<div id="comment">
		<!-- 来必力City版安装代码 -->
		<div id="lv-container" data-id="city" data-uid="MTAyMC8zMDA5MC82NjQ1">
		<script type="text/javascript">
		   (function(d, s) {
		       var j, e = d.getElementsByTagName(s)[0];

		       if (typeof LivereTower === 'function') { return; }

		       j = d.createElement(s);
		       j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
		       j.async = true;

		       e.parentNode.insertBefore(j, e);
		   })(document, 'script');
		</script>
		<noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
		</div>
		<!-- City版安装代码已完成 -->
	</div>



      
      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2017/06/22/Python图像处理库到底用哪家/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">上一篇</strong>
      <div class="article-nav-title">
        
          Python图像处理库到底用哪家
        
      </div>
    </a>
  
  
    <a href="/2017/06/12/Jarvis-一个有人情味的人工智能机器人/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">下一篇</strong>
      <div class="article-nav-title">Jarvis: 一个有人情味的人工智能机器人</div>
    </a>
  
</nav>

  
</article>

<!-- Table of Contents -->

  <aside id="toc-sidebar">
    <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录</strong>
    
        <ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#为什么用Go"><span class="nav-number">1.</span> <span class="nav-text">为什么用Go</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Go入门第一课，反射调用函数"><span class="nav-number">2.</span> <span class="nav-text">Go入门第一课，反射调用函数</span></a></li></ol>
    
    </div>
  </aside>
</section>
        
      </div>
      
      <footer id="footer">
  

  <div class="container">
      	<div class="row">
	      <p> Powered by <a href="http://www.luoli-luoli.com/" target="_blank">萝莉萝莉</a> and <a href="http://www.luoli-luoli.com/sia" target="_blank">Sia</a> </p>
	      <p id="copyRightEn">Copyright &copy; 2017 - 2018 Jin Tian All Rights Reserved.</p>
	      
	      
    		<p class="busuanzi_uv">
				访客数 : <span id="busuanzi_value_site_uv"></span> |  
				访问量 : <span id="busuanzi_value_site_pv"></span>
		    </p>
  		   
		</div>

		
  </div>
</footer>


<!-- min height -->

<script>
    var wrapdiv = document.getElementById("wrap");
    var contentdiv = document.getElementById("content");
    var allheader = document.getElementById("allheader");

    wrapdiv.style.minHeight = document.body.offsetHeight + "px";
    if (allheader != null) {
      contentdiv.style.minHeight = document.body.offsetHeight - allheader.offsetHeight - document.getElementById("footer").offsetHeight + "px";
    } else {
      contentdiv.style.minHeight = document.body.offsetHeight - document.getElementById("footer").offsetHeight + "px";
    }
</script>
    </div>
    <!-- <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
    <a href="/categories" class="mobile-nav-link">Categories</a>
  
    <a href="/tags" class="mobile-nav-link">Tags</a>
  
    <a href="/about" class="mobile-nav-link">About</a>
  
    <a href="http://luoli-luoli.com/chat" class="mobile-nav-link">Chat</a>
  
</nav> -->
    

<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true
    }
  });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>

<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/scripts.js"></script>




  <script src="/js/dialog.js"></script>








	<div style="display: none;">
    <script src="https://s95.cnzz.com/z_stat.php?id=1260716016&web_id=1260716016" language="JavaScript"></script>
  </div>



	<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
	</script>






  </div>

  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h2 class="modal-title" id="myModalLabel">设置</h2>
      </div>
      <hr style="margin-top:0px; margin-bottom:0px; width:80%; border-top: 3px solid #000;">
      <hr style="margin-top:2px; margin-bottom:0px; width:80%; border-top: 1px solid #000;">


      <div class="modal-body">
          <div style="margin:6px;">
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" onclick="javascript:setFontSize();" aria-expanded="true" aria-controls="collapseOne">
              正文字号大小
            </a>
          </div>
          <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
          <div class="panel-body">
            您已调整页面字体大小
          </div>
        </div>
      


          <div style="margin:6px;">
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" onclick="javascript:setBackground();" aria-expanded="true" aria-controls="collapseTwo">
              夜间护眼模式
            </a>
        </div>
          <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
          <div class="panel-body">
            夜间模式已经开启，再次单击按钮即可关闭 
          </div>
        </div>

        <div>
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="true" aria-controls="collapseThree">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;关 于&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>
        </div>
         <div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">
          <div class="panel-body">
            Jin Tian
          </div>
          <div class="panel-body">
            Copyright © 2018 Jintian All Rights Reserved.
          </div>
        </div>
      </div>


      <hr style="margin-top:0px; margin-bottom:0px; width:80%; border-top: 1px solid #000;">
      <hr style="margin-top:2px; margin-bottom:0px; width:80%; border-top: 3px solid #000;">
      <div class="modal-footer">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
      </div>
    </div>
  </div>
</div>
  
  <a id="rocket" href="#top" class=""></a>
  <script type="text/javascript" src="/js/totop.js?v=1.0.0" async=""></script>
  
    <a id="menu-switch"><i class="fa fa-bars fa-lg"></i></a>
  
</body>
</html>